package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 */
@Controller
public class FileUpload {
    /**
     * 单文件上传并存放到本地
     */
    @ResponseBody
    @RequestMapping("/upload01")
    //MultipartFile的参数名称要与表单中type为file类型的name保持一致。
    public void fileUpload01(String name, MultipartFile upload) {
        try {
            System.out.println("name = " + name);
            //获得上传文件的名称
            String fileName = upload.getOriginalFilename();
            System.out.println("fileName = " + fileName);
            upload.transferTo(new File("F:\\Developer\\Java\\Java-Projects\\SSM\\SpringMVC-ResponseAndRequest\\src\\main\\webapp\\jsp\\file\\" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 多文件上传并存放到本地
     */
    @ResponseBody
    @RequestMapping("/upload02")
    public void fileUpload02(String name, MultipartFile[] upload) {
        try {
            for (MultipartFile file : upload) {
                //获得上传文件的名称
                String filename = file.getOriginalFilename();
                System.out.println("filename = " + filename);
                file.transferTo(new File("F:\\Developer\\Java\\Java-Projects\\SSM\\SpringMVC-ResponseAndRequest\\src\\main\\webapp\\jsp\\file\\" + filename));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
